package com.nowcoder.code.lcof;

import com.algorithm.model.TreeNode;

public class JZ68 {

    public int lowestCommonAncestor(TreeNode root, int p, int q) {
        return preOrder(root, p, q);
    }


    public int preOrder(TreeNode root, int p, int q) {
        if (root == null) {
            return -1;
        }
        int left = preOrder(root.left, p, q);
        int right = preOrder(root.right, p, q);

        if (left != -1 && right != -1) {
            return root.val;
        }

        if (root.val == p || root.val == q) {
            return root.val;
        }

        return Math.max(left, right);

    }


}
